package com.x.compute.common.function;

import cn.hutool.core.util.BooleanUtil;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.type.AviatorJavaType;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.AviatorRuntimeJavaType;
import com.googlecode.aviator.runtime.type.AviatorType;

import java.util.Map;

/**
 * 自定义IF函数
 * 函数示例：IF(arg1, arg2, arg3)
 * @author xuxin
 */
public class IfFunction extends AbstractFunction {

    @Override
    public String getName() {
        return "IF";
    }

    /**
     * 函数处理逻辑
     * @param env 变量上下文
     * @param arg1 判断条件，boolean类型
     * @param arg2 arg1为true时返回的结果
     * @param arg3 arg1为false时返回的结果
     * @return
     */
    @Override
    public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2, AviatorObject arg3) {
        Object value = arg1.getValue(env);
        Boolean condition = false;
        if (value instanceof Boolean) {
            condition = (Boolean) value;
        }else if (value instanceof String){
            condition = BooleanUtil.toBoolean(value.toString());
        }
        Object trueValue = handle(arg2,env);
        Object falseValue = handle(arg3,env);
        return condition ? AviatorRuntimeJavaType.valueOf(trueValue) : AviatorRuntimeJavaType.valueOf(falseValue);
    }

    /**
     * 变量值处理
     * @param arg 参数对象
     * @param env 变量上下文
     * @return
     */
    private Object handle(AviatorObject arg, Map<String, Object> env){
        Object value = arg.getValue(env);
        return value == null && arg.getAviatorType() == AviatorType.JavaType ? ((AviatorJavaType)arg).getName() : value;
    }
}
